import {Button, Descriptions, Divider, Image, Input, message, Modal, Popconfirm, Select, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {del, getPurchaseDetail, orderOut, purchaseList, revoke,getStockList,addOneDetail,exportDetails} from './service';

import Access from '@/components/Access/Access';

import CreateForm from "./components/CreateForm";
import "./index.css";

import {CheckSquareOutlined, DownloadOutlined, EnvironmentOutlined} from '@ant-design/icons';
import GDMap from "@/components/AMap/GDMap";
import styles from "@/global.less";
import {storeBaseList} from "@/pages/OrderManagement/StoreOrder/service";
import {saveFileAs} from "@/utils/utils";
import {getConfig, setConfig} from "@/pages/SupplyChainManagement/PurchaseManagement/PurchaseList/OrderList/service";


const TableList = (props) => {
  const actionRef = useRef();

  const [count, setCount] = useState();
  const [storeArray, setStoreArray] = useState([]);
  const [purchaseDetail, handlePurchaseDetail] = useState(false);
  const [purchaseDetails, handlePurchaseDetails] = useState(false);
  const [record, setRecord] = useState({});
  const [details, setDetails] = useState({});
  const [mySelectedRowKeys, handleMySelectedRowKeys] = useState([]);
  const [mapModalVisible, handleMapModalVisible] = useState(false);
  const [order, setOrder] = useState({});
  const [mapStores, setMapStores] = useState([]);
  const [orderOutLoading, handleOrderOutLoading] = useState(false);
  const [takeType, setTakeType] = useState(null);

  const [addDetails, handleAddDetails] = useState(false);
  const [addDetailsLoading, handleAddDetailsLoading] = useState(false);
  const [stockList, setStockList] = useState([]);
  const [addDetailsStore, setAddDetailsStore] = useState({});
  const [outDetailsModal, handleOutDetailsModal] = useState(false);

  const confirm = Modal.confirm;
  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    getStore();
  }, []);

  const simpleColumns = [
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeName',
      hideInSearch: true,
    },
    {
      title: '一级区域',
      dataIndex: 'regionParentName',

    },
    {
      title: '二级区域',
      dataIndex: 'regionName',

    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
      valueEnum: {
        true: {
          text: '统采',
          status: 'Success',
        },
        false: {
          text: '地采',
          status: 'Error',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '采购中',
          status: 'Success',
        },
        1: {
          text: '待审批',
          status: 'Error',
        },
        2: {
          text: '待分配',
          status: 'Error',
        },
        3: {
          text: '已分配',
          status: 'Error',
        },
        4: {
          text: '待收货',
          status: 'Error',
        },
        5: {
          text: '已收货',
          status: 'Error',
        },
        51: {
          text: '部分收货',
          status: 'Error',
        },
        9: {
          text: '已完成',
          status: 'Success',
        },
        99: {
          text: '已驳回',
          status: 'Error',
        },
      },
    },
    {
      title: '收货方式',
      dataIndex: 'takeType',
      valueEnum: {
        0: {
          text: '仓库发货',
          status: 'Success',
        },
        1: {
          text: '自提',
          status: 'Error',
        },
      },
    },
    {
      title: '日期',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '收货地址',
      dataIndex: 'address',
      hideInSearch: true,
    },
    {
      title: '备注',
      dataIndex: 'remake',
      hideInSearch: true,
    },
  ];

  const orderConfirmColumns = simpleColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {

        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Access accessKey={"@unifyPurchaseList_add_details"}>
                <Button
                  type="primary"
                  danger
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    setAddDetailsStore(item);
                    handleAddDetails(true);
                  }}
                >
                  添加明细
                </Button>
              </Access>
            </div>
          </>
        );
      },
    },
  ]);
  const columns = simpleColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Access accessKey={"@unifyPurchaseList_details"}>
                <Button
                  type="primary"
                  danger
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    setRecord(item);
                    let params = {
                      purchaseId: item.id
                    };
                    getPurchaseDetail(params).then(res => {
                      setDetails(res.data);
                      handlePurchaseDetail(true);
                    });
                  }}
                >
                  详情
                </Button>
              </Access>

              {
                (item.status === 1 || item.status === 2) ? (<>
                  <Access accessKey={"@unifyPurchaseList_revoke"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        let params = {
                          id: item.id
                        };
                        revoke(params).then(res => {
                          if (res?.code === 0) message.info("撤销成功");
                          actionRef.current.reload();
                        })
                      }}
                    >
                      撤销
                    </Button>
                  </Access>

                </>) : null
              }
              {
                item.status === 99 ? (<>
                  <Access accessKey={"@unifyPurchaseList_del"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        Modal.confirm({
                          title: '注意',
                          content: '确认要删除此采购单吗',
                          onOk() {
                            let params = {
                              id: item.id
                            };
                            del(params).then(res => {
                              if (res?.code === 0) message.info("删除成功");
                              actionRef.current.reload();
                            })
                          },
                          onCancel() {},
                        });
                      }}
                    >
                      删除
                    </Button>
                  </Access>

                </>) : null
              }
            </div>
          </>
        );
      },
    },
  ]);

  const showConfirm = (record) => {
    confirm({
      title: '注意',
      content: '确认要修改[' + record.title + ']的分配数量为[' + record.outStock + ']吗?',
      onOk() {
        console.log(record);
      },
      onCancel() {

      },
    });
  };
  const detailShowColumns = [
    {
      title: '产品',
      dataIndex: 'title',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },
    {
      title: '采购数量',
      dataIndex: 'value',
      hideInSearch: true,
    },

    {
      title: '发货数量',
      hideInSearch: true,
      dataIndex: 'outStock',
    },
    {
      title: '收货数量',
      dataIndex: 'realStock',
      hideInSearch: true,
    },
    {
      title: '成本',
      dataIndex: 'dataPrice',
      hideInSearch: true,
    },
  ];
  const detailColumns = [
    {
      title: '产品',
      dataIndex: 'title',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },
    {
      title: '采购数量',
      dataIndex: 'value',
      hideInSearch: true,
    },
    {
      title: '库存',
      dataIndex: 'sysStock',
      hideInSearch: true,
    },
    {
      title: '分配数量',
      hideInSearch: true,
      dataIndex: 'outStock',
      render: (dom, record) => {
        let flag = false;
        return <Input
          placeholder={record.value}
          onChange={(e) => {
            record.outStock = e.target.value;
            flag = true;
          }
          }
          onPressEnter={() => {
            flag = false;
            showConfirm(record);
          }
          }
          onBlur={() => {
            if (record.outStock && flag) {
              flag = false;
              showConfirm(record)
            }
          }
          }
        />;
      },
    },
    {
      title: '采购成本',
      dataIndex: 'dataPrice',
      hideInSearch: true,
    },
    {
      title: '收货数量',
      dataIndex: 'realStock',
      hideInSearch: true,
    },

  ];
  const stockListColumns = [
    {
      title: '品名',
      dataIndex: 'goodsName',
      width: 220,
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      width: 120,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      width: 120,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '占用库存',
      dataIndex: 'robStock',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        const popFim = (
          <div key="popFim" style={{display: 'flex', justifyContent: 'space-between', alignContent: 'center'}}>
            <div>数量:</div>
            <Input
              placeholder="请输入采购数量"
              style={{width: 140, height: 30, marginLeft: 10}}
              onChange={(e) => {
                return (item.current = e.target.value);
              }}
            />
          </div>
        );

        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Popconfirm
                icon={null}
                okText="确认"
                cancelText="取消"
                title={popFim}
                onConfirm={() => {
                  let details = [{
                    id:item.id,
                    stock:item.current
                  }];
                  let params = {
                    purchaseId:addDetailsStore.id,
                    details
                  };
                  addOneDetail(params).then(res=>{
                    if (res?.code === 0) message.info("添加成功");
                    actionRef.current.reload();
                    handleMySelectedRowKeys([]);
                    handlePurchaseDetails(false);
                  })
                }}
              >
                <a>添加明细</a>
              </Popconfirm>
            </div>
          </>
        );
      },
    },
  ];
  const outDetailsColumns = [

    {
      title: '采购时间',
      dataIndex: 'purchaseDate',
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '采购时间为必选项',
          },
        ],
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
  ];
  let cancleRowKeys = [];
  const onSelect = (record, selected) => {
    if (!selected) {
      cancleRowKeys = [record.id];
    }
  };
  const onMulSelect = (selected, selectedRows, changeRows) => {
    if (!selected) {
      cancleRowKeys = changeRows.map((item) => item.id);
    }
  };
  const onChange = (selectedRowKeys, selectedRows) => {
    let keys = [];
    const groups = selectedRows.reduce((groups, row) => {
      const key = row.takeType;
      if (!groups[key]) {
        groups[key] = [];
      }
      groups[key].push(row);
      return groups;
    }, {});
    for (let key in groups) {
      keys.push(key);
    }
    if (keys.length > 1) {
      message.error("只能批量处理同一收货类型的订单!");
      handleMySelectedRowKeys([]);
    } else {
      setTakeType(keys[0]);
      if (cancleRowKeys.length) {
        const keys = mySelectedRowKeys.filter((item) => !cancleRowKeys.includes(item));
        handleMySelectedRowKeys(keys);
        cancleRowKeys = [];
      } else {
        handleMySelectedRowKeys([...new Set(mySelectedRowKeys.concat(selectedRowKeys))]);
      }
    }
  };

  const alertRender = ({selectedRowKeys, selectedRows, onCleanSelected}) => {
    order.totalStock = selectedRows.map(row => row.totalStock).reduce((preVal, currVal) => preVal + currVal, 0);
    let details = selectedRows.map(row => row.details).reduce((preVal, currVal) => preVal.concat(currVal), []);
    let tempMap = new Map();
    details.forEach(detail => {
      if (tempMap.has(detail.title)) {
        let temp = tempMap.get(detail.title);
        temp.value = temp.value + detail.value;
        tempMap.set(detail.title, temp)
      } else {
        tempMap.set(detail.title, {
          value: detail.value,
          sysStock: detail.sysStock,
          robStock:detail.robStock
        })
      }
    });

    let tempList = [];
    tempMap.forEach((v, k) => {
      tempList.push({
        v, k
      })
    });
    return (
      <>
        预览:
        {
          tempList.map(({v, k}) => {
            return (
              <div>
                <Tag color="green">采购产品：{k}</Tag>
                <Tag color="red">采购数：{v.value}</Tag>
                {
                  v.sysStock ? <Tag color="blue">库存：{v.sysStock}</Tag> : null
                }
                {
                  v.robStock ? <Tag color="blue">已占：{v.robStock}</Tag> : null
                }
              </div>
            )
          })
        }
      </>
    );
  };

  const alertOptionRender = ({selectedRowKeys, selectedRows, onCleanSelected}) => {
    setMapStores(selectedRows);
    if (takeType) {
      return takeType === "1" ? (
        <>
          <div>
            <Button
              key="approveBtn"
              onClick={() => {
                handlePurchaseDetails(true);
              }}
            >
              <CheckSquareOutlined/>采购出库
            </Button>
          </div>
        </>
      ) : (
        <>
          <div>
            <Button
              key="mapBtn"
              onClick={() => {
                handleMapModalVisible(true);
              }}
            >
              <EnvironmentOutlined/>路线预览
            </Button>
            <Divider type="vertical"/>
            <Button
              key="approveBtn"
              onClick={() => {
                handlePurchaseDetails(true);
              }}
            >
              <CheckSquareOutlined/>采购出库
            </Button>
          </div>
        </>
      );
    } else {
      return null;
    }
  };
  const getStatusStr = (status) => {
    switch (status) {
      case 0:
        return "采购中";
      case 1:
      case 7:
        return "待审批";
      case 2:
        return "待发货";
      case 3:
        return "已发货";
      case 4:
        return "待收货";
      case 5:
        return "已完成";
      case 6:
        return "已驳回";
      case 9:
        return "已完成";
      case 99:
        return "已驳回";
    }
  };

  const detailRender = (e) => {
    return <>
      <ProTable
        rowKey="key"
        scroll={{x: 1400}}
        bordered
        dataSource={e.details}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={detailColumns}
      />
    </>
  };

  const getOrderParams = () => {
    let orderDetails = [];
    mapStores.forEach(item => {
      item.details.forEach(detail => {
        let orderDetail = {
          purchaseId: item.id,
          detailId: detail.detailId,
          storeId: item.storeId,
        };
        if (detail.outStock) {
          orderDetail.outStock = detail.outStock
        } else {
          orderDetail.outStock = detail.value
        }
        orderDetails.push(orderDetail)
      })
    });
    order.details = orderDetails;
    return order;
  };

  return (
    <PageContainer>
      <ProTable
        headerTitle="采购列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1400}}
        bordered
        request={(params, sorter, filter) => purchaseList({...params, sorter, filter})}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        toolBarRender={() => [
          <Access accessKey={"@purchase_list_export"}>
            <Button
              key="purchase_list_export"
              type="primary"
              onClick={() => {
                handleOutDetailsModal(true);
              }}
            >
              <DownloadOutlined/> 导出统采列表
            </Button>
          </Access>,
          <Access accessKey={"@unifyPurchaseList_change_config"}>
            <Button
              key="unifyPurchaseList_change_config"
              type="primary"
              onClick={() => {
                getConfig(1).then(res => {
                  let dto = res.data;
                  let curPurchaseNum = dto.purchaseNumber;
                  const popFim = (
                    <div key="popFim">
                      <Input
                        placeholder={(curPurchaseNum > 0) ? curPurchaseNum : "请输入"}
                        style={{width: 140, height: 30, marginLeft: 10}}
                        onChange={(e) => {
                          dto.purchaseNumber = e.target.value;
                        }}
                      />
                    </div>
                  );
                  Modal.confirm({
                    title: '统采频率',
                    content: popFim,
                    icon: '',
                    onOk() {
                      setConfig(dto).then(res => {
                        message.info("修改成功");
                      })
                    },
                    onCancel() {

                    },
                  });
                })

              }}
            >
              统采限制频率
            </Button>
          </Access>

        ]}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        rowSelection={{
          fixed: true,
          selectedRowKeys: mySelectedRowKeys,
          onSelect, //用户手动选择/取消选择某行的回调
          onSelectMultiple: onMulSelect, //用户使用键盘 shift 选择多行的回调
          onSelectAll: onMulSelect, //用户手动选择/取消选择所有行的回调
          onChange, //选中项发生变化时的回调
          getCheckboxProps: record => {
            return {
              disabled: record.status !== 2
            };
          },
        }}
        tableAlertRender={alertRender}
        tableAlertOptionRender={alertOptionRender}
        footer={() => {
          return (
            <div key="settleFooter" style={{ color: 'red' }}>
              <span>说明：</span>
              <div>* 【撤回】可撤回审批中或审批通过的订单,审批中的订单撤回后企业微信审批流程无法撤回</div>
              <div>* 【分配】已分配采购单不可撤回，只能在出库前打回，已出库不可撤回</div>
              <div>* 【删除】撤回的订单可修改重新提交，如果要重新发起申请，可在驳回该申请后删除该次采购申请</div>
              <div>* 【限制】采购频率为每店铺两周一次</div>
            </div>
          );
        }}
      />

      <CreateForm width={1300} onCancel={() => handlePurchaseDetail(false)} modalVisible={purchaseDetail}
                  btn_view={null}>
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">采购详情</Divider>
          <Descriptions column={2}>
            <Descriptions.Item label="状态">
              {details ? getStatusStr(details.status) : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="总数">
              {details ? details.totalPrice : '暂无'}
            </Descriptions.Item>
          </Descriptions>

          <ProTable
            headerTitle="详情列表"
            rowKey="key"
            scroll={{x: 1400}}
            bordered
            dataSource={details.details}
            search={false}
            toolBarRender={false}
            pagination={false}
            columns={detailShowColumns}
          />
          <Divider orientation="left">收货凭证</Divider>
          <Image.PreviewGroup>
            {
              details.files?.map(img => {
                return <Image key={img.id} width={100} height={100} src={img.img}/>
              })
            }
          </Image.PreviewGroup>
        </div>
      </CreateForm>
      <CreateForm
        title="路线预览"
        onCancel={() => {
          handleMapModalVisible(false);
        }}
        modalVisible={mapModalVisible}
        width={1200}
        btn_view={
          <div key="settleFooter" style={{color: 'red', textAalign: 'center'}}>
            <div>* 仅供参考</div>
          </div>
        }
      >
        <GDMap data={mapStores}/>
      </CreateForm>
      <CreateForm
        width={1300}
        onCancel={() => handlePurchaseDetails(false)}
        modalVisible={purchaseDetails}
        btn_view={(
          <div className={styles.footer_btn}>
            <Button danger type="primary" onClick={() => {
              handlePurchaseDetails(false)
            }}>
              取消
            </Button>
            <Access accessKey={"@unifyPurchaseList_orderOut"}>
              <Button loading={orderOutLoading} type="primary" onClick={() => {
                handleOrderOutLoading(true);
                let orderParams = Object.assign(takeType === "1" ? ({takeType: 1}) : ({takeType: 0}), getOrderParams());
                orderOut(orderParams).then(res => {
                  if (res?.code === 0){
                    handleMySelectedRowKeys([]);
                    handlePurchaseDetails(false);
                    handleOrderOutLoading(false);
                    actionRef.current.reload();
                  }
                });
              }}>
                提交
              </Button>
            </Access>

          </div>
        )}
      >
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">采购详情</Divider>
          <ProTable
            headerTitle="详情列表"
            rowKey="id"
            scroll={{x: 1400}}
            bordered
            dataSource={mapStores}
            search={false}
            toolBarRender={false}
            pagination={false}
            columns={orderConfirmColumns}
            expandedRowRender={detailRender}
            defaultExpandAllRows
          />

        </div>
      </CreateForm>
      <CreateForm
        width={1300}
        onCancel={() => handleAddDetails(false)}
        modalVisible={addDetails}
        btn_view={false}
      >
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">添加明细</Divider>
          <ProTable
            headerTitle="库存列表"
            rowKey="id"
            search={{
              labelWidth: 80,
            }}
            bordered
            request={(params, sorter, filter) => {
              params.bizType = addDetailsStore.bizType;
              return getStockList({...params, sorter, filter})
            }}
            postData={(payload) => {
              const {list, total} = payload;
              setCount(total);
              return list || [];
            }}
            toolBarRender={() => [
            ]}
            columns={stockListColumns}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: false,
              showTitle: false,
              total: count,
              showTotal: (total) => `共${total}条`,
            }}
          />
        </div>
      </CreateForm>
      <CreateForm
        title={'导出信息'}
        width={800}
        btn_view={null}
        onCancel={() => {
          handleOutDetailsModal(false);
        }}
        modalVisible={outDetailsModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutDetailsModal(false);
            exportDetails(value).then(res=>{
              if (res){
                saveFileAs(res, '采购记录');
              }
            })
          }}
          rowKey={r=>r.id}
          bordered
          type="form"
          columns={outDetailsColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
